//
//  PlayColorVC.swift
//  GameDemo
//
//  Created by 勇胡 on 2025/8/13.
//

import Foundation
import UIKit
import SnapKit

class PlayColorVC: BaseVC {
    public var gameModel:GameModel!
    
    private var row1BgView:UIStackView!
    private var row2BgView:UIStackView!
    private var row1:[CardView] = []
    private var row2:[CardView] = []
    private var selectedIconName = ""
    private var resultImgView:UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .black
        // 强制横屏
        UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue, forKey: "orientation")
        setupUI()
        
        let resetButton = UIButton(type: .custom)
        resetButton.setTitle("clear", for: .normal)
        resetButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        resetButton.setTitleColor(.white, for: .normal)
        resetButton.backgroundColor = UIColor(white: 0.15, alpha: 1)
        resetButton.layer.cornerRadius = 5
        resetButton.layer.masksToBounds = true
        resetButton.addTarget(self, action: #selector(onClear), for: .touchUpInside)
        self.view.addSubview(resetButton)
        resetButton.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-15)
            make.top.equalToSuperview().offset(20)
            make.size.equalTo(CGSize(width: 60, height: 35))
        }
        
        let showButton = UIButton(type: .custom)
        showButton.setTitle("show", for: .normal)
        showButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        showButton.setTitleColor(.white, for: .normal)
        showButton.backgroundColor = UIColor(white: 0.15, alpha: 1)
        showButton.layer.cornerRadius = 5
        showButton.layer.masksToBounds = true
        showButton.addTarget(self, action: #selector(showAll), for: .touchUpInside)
        self.view.addSubview(showButton)
        showButton.snp.makeConstraints { make in
            make.right.equalTo(resetButton.snp.left).offset(-35)
            make.top.equalTo(resetButton.snp.top)
            make.size.equalTo(CGSize(width: 60, height: 35))
        }
        
        resultImgView = UIImageView()
        resultImgView.isHidden = true
        resultImgView.layer.cornerRadius = 10
        resultImgView.layer.masksToBounds = true
        
        self.view.addSubview(resultImgView)
        resultImgView.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 400, height: 400))
            make.center.equalToSuperview()
        }
    }
    
    @objc func showAll(){
        for itemView in row1{itemView.show()}
        for itemView in row2{itemView.show()}
    }
    
    @objc func onClear(){
        for itemView in row1{itemView.reset()}
        for itemView in row2{itemView.reset()}
        selectedIconName = ""
    }
    
    private func updateResult(isError:Bool){
        resultImgView.isHidden = false
        if isError{
            
            resultImgView.image = UIImage(named: "错误")
        }else{
            resultImgView.image = UIImage(named: "正确")
        }
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1) {
            self.resultImgView.isHidden = true
        }
    }
    
    private func setupUI(){
        row1BgView = createStackView()
        
        let rowItemCount = gameModel.words.count
        let itemW:CGFloat = (self.view.frame.size.height - CGFloat(rowItemCount+1)*15) / CGFloat(rowItemCount)
        //打乱顺序
        let wordItemList = gameModel.words.shuffled()
        let top_bottom_space:CGFloat = Utils.isPad() ? 40 : 20
        let itemMaxH:CGFloat = self.view.width * 0.4
        let itemRealH:CGFloat = min(itemW*1.5, itemMaxH)
        
        for wordItem in wordItemList{
            let view = CardView(frame: .zero)
            view.isPlaySoundWhenTap = true
            view.update(wordItem: wordItem)
            view.onSelectIconBlock = {[weak self]icon in
                guard let `self` = self else { return }
                self.selectedIconName = icon
                
            }
            row1BgView.addArrangedSubview(view)
            view.translatesAutoresizingMaskIntoConstraints = false
            row1.append(view)
        }
        view.insertSubview(row1BgView, at: 0)
        
        row1BgView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.centerY.equalToSuperview().offset(-itemRealH*0.5-top_bottom_space*0.5)
            make.height.equalTo(itemRealH)
        }
        
        
        row2BgView = createStackView()
        let wordItemList2 = wordItemList.shuffled()
        for wordItem in wordItemList2 {
            let view = CardView(frame: .zero)
            view.update(title: "\(wordItem.word)")
            row2BgView.addArrangedSubview(view)
            view.onSelectTextBlock = {[weak self]word in
                guard let `self` = self else { return }
                //错误
                if word != self.selectedIconName{
                    Utils.playErrorSound()
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1.5) {
                        self.updateResult(isError: true)
                        view.reset()
                    }
                }else{
                    Utils.playSuccessSound()
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1.5) {
                        self.updateResult(isError: false)
                    }
                    
                }
            }
            view.translatesAutoresizingMaskIntoConstraints = false
            row2.append(view)
        }
        view.insertSubview(row2BgView, at: 0)
        row2BgView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(row1BgView.snp.bottom).offset(top_bottom_space)
            make.height.equalTo(row1BgView.snp.height)
        }
    }
    
    private func createStackView()->UIStackView{
        let stackView = UIStackView()
        stackView.axis = .horizontal // 水平排列
        stackView.alignment = .fill // 子视图填充栈视图的高度
        stackView.distribution = .fillEqually // 子视图平均分配宽度
        stackView.spacing = 15 // 子视图之间的间距
        stackView.isLayoutMarginsRelativeArrangement = true
        return stackView
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .landscape
    }
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .landscapeRight
    }
    
    override var shouldAutorotate: Bool {
        return true
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        UIViewController.attemptRotationToDeviceOrientation()
    }
}

